import json
import time
from datetime import datetime
import requests

all_symbol = ['BTC-USD','ETH-USD']

# 获取订单簿数据
def get_capital_rate_write():
    for symbol in all_symbol:
        while(1):
            try:
                url = "https://indexer.dydx.trade/v4/perpetualMarkets?ticker="+symbol
                response = requests.request("GET", url)
                # 将订单簿数据写入TXT文件，a追加模式
                current_time = datetime.now().strftime('%m_%d_%H')
                with open('./capital_rate/'+current_time+'_'+symbol+'.txt', 'a') as file:
                    file.write(response.text + '\n')
                time.sleep(1)
                break
            except Exception as e:
                print(str(symbol)+"  dydx 获取数据失败 重新获取")

# 获取所有 代币名称
def get_token_name():
    global all_symbol

    url = "https://indexer.dydx.trade/v4/sparklines?timePeriod=SEVEN_DAYS"

    response = requests.request("GET", url)

    print(all_symbol)
    

    all_symbol = list(response.json().keys())

    print(all_symbol)


def get_capital_rate_dydx(all_token):
    #get_token_name()
    #for symbol in all_symbol:
    result=[]
    for symbol in all_token:
        try_time=5
        while(try_time):
            try:
                url = "https://indexer.dydx.trade/v4/perpetualMarkets?ticker="+symbol
                response = requests.request("GET", url).json()
                timestamp = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
                result.append({"time":timestamp,"trading_pair": symbol,"platform":"dydx","funding":float(response["markets"][symbol]["nextFundingRate"])*100})
                time.sleep(0.3)
                break
            except Exception as e:
                print(str(symbol)+" dydx 获取数据失败 重新获取 剩余尝试次数 "+str(try_time))
                try_time=try_time-1
    return result